package logic

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/api/internal/dto"
	"github.com/vueadmin/app/api/internal/service"
	"github.com/vueadmin/app/api/internal/svc"
	"github.com/vueadmin/app/api/internal/vo"
	"github.com/vueadmin/pkg/cache"
	"github.com/vueadmin/pkg/jwt"
	"github.com/vueadmin/pkg/sms"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"time"
)

type membeLogic struct {
	ctx    *gin.Context
	svcCtx *svc.ServiceContext
}

func NewMembeLogic(ctx *gin.Context, svcCtx *svc.ServiceContext) *membeLogic {
	return &membeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

/**
 * @description(数据列表)
 * @buildcode(true)
 */
func (p membeLogic) GetPageList(req *dto.MembePageReq) ([]*vo.MembeList, int64, error) {
	s := service.NewMembeService(p.svcCtx)
	return s.GetPageList(req)
}

/**
 * @description(修改)
 * @buildcode(true)
 */
func (p membeLogic) Update(req *dto.MembeUpdateReq) error {
	s := service.NewMembeService(p.svcCtx)
	return s.Update(req)
}

/**
 * @description(删除)
 * @buildcode(true)
 */
func (p membeLogic) Delete(req *dto.MembeDeleteReq) error {
	s := service.NewMembeService(p.svcCtx)
	return s.Delete(req)
}

/**
 * @description(查看详情)
 * @buildcode(true)
 */
func (p membeLogic) Detail(req *dto.MembeDetailReq) (*vo.MembeDetail, error) {
	s := service.NewMembeService(p.svcCtx)
	return s.Detail(req)
}

/**
 * @description(重置密码)
 * @buildcode(true)
 */
func (p membeLogic) ResetPwd(req *dto.MembeResetPwdReq) error {
	s := service.NewMembeService(p.svcCtx)
	return s.ResetPwd(req)
}

/**
 * @description(用户登录)
 * @buildcode(true)
 */
func (p membeLogic) Login(req *dto.MembeLoginReq) (string, error) {
	s := service.NewMembeService(p.svcCtx)
	info, err := s.Login(req)
	if err != nil {
		return "", err
	}
	token, createTokenError := jwt.NewJwt(conv.String(p.svcCtx.Config.Jwt)).CreateToken(info)
	if createTokenError != nil {
		return "", createTokenError
	}
	return token, nil
}

/**
 * @description(短信验证码登录)
 * @buildcode(true)
 */
func (p membeLogic) Loginsms(mobile string) (string, error) {
	s := service.NewMembeService(p.svcCtx)
	info, err := s.Loginsms(mobile)
	if err != nil {
		return "", err
	}
	token, createTokenError := jwt.NewJwt(conv.String(p.svcCtx.Config.Jwt)).CreateToken(info)
	if createTokenError != nil {
		return "", createTokenError
	}
	return token, nil
}

/**
 * @description(发送验证码)
 * @buildcode(true)
 */
func (p membeLogic) SendSms(req *dto.MembeSendSmsReq) (string, error) {
	verify := utils.GenerateSmsCode(6)
	if err := sms.NewAliSms(conv.String(p.svcCtx.Config.AliSms)).Send(req.Mobile, verify); err != nil {
		p.svcCtx.Log.Error("Ali短信发送失败:", err)
		return "", errors.New("发送失败")
	}
	req.Verify = verify
	req.Key = utils.Md5(req.Mobile + conv.NowDateTime())
	if err := cache.New(p.svcCtx.Redis).Set(req.Key, conv.String(req), 600*time.Second); err != nil {
		return "", errors.New("发送失败")
	}
	return req.Key, nil
}
